package com.cxl.live.aop;

import com.cxl.live.base.RequestModel;
import com.cxl.live.base.ResultModel;
import com.cxl.live.constants.BaseEnums;
import com.cxl.live.constants.Constants;
import com.cxl.live.exception.BusinessException;
import com.cxl.live.system.dto.UserInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @Description: LoginAopAnnotation
 * @Author: ChenXueLi
 * @Date: 2018-10-05 17:56
 */
@Aspect
@Component
public class LoginAspect {

    @Pointcut("@annotation(com.cxl.live.aop.LoginAop)")
    public void loginAop() {
    }

    @Before("loginAop() && @annotation(data)")
    public void doBefore(JoinPoint point, LoginAop data) throws Throwable {
        // 获取request以及seesion
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        HttpSession session = request.getSession();

        // 获取访问ip

        // 获得当前用户
        UserInfo loginUser = (UserInfo) session.getAttribute(Constants.LOGIN_INFO);
        if (loginUser == null) {
            // 登录超时或未登录
            throw new BusinessException(BaseEnums.NO_LOGIN);
        }

        // 获取返回数据的模型
        RequestModel requestModel = new RequestModel();
        if (point.getArgs() != null) {
            for (Object obj : point.getArgs()) {
                if (obj != null && obj.getClass() == ResultModel.class) {
                    requestModel = (RequestModel) obj;
                    break;
                }
            }
        }

        // 创建返回数据对象
        ResultModel resultModel = new ResultModel();
        // 添加用户信息
        resultModel.setUserInfo(loginUser);
        requestModel.setResultModel(resultModel);
    }

}
